from django.shortcuts import render, redirect
from .models  import UserInfo
from df_goods.models import  GoodsInfo
from django.http import JsonResponse,HttpResponseRedirect
#密码加密模块
from hashlib import sha1
from df_user import user_decorator
from df_order.models import OrderInfo
# Create your views here.

#注册
def register(request):
    return render(request,'df_user/register.html', {'title':'注册'})

#注册处理
def register_handle(request):
    #接受用户输入
    post = request.POST
    uname = post.get('user_name')
    upwd = post.get('pwd')
    cpwd = post.get('cpwd')
    email = post.get('email')
    #判断两次密码
    if upwd !=cpwd:
        return redirect('/user/register')

    #密码加密
    s1 = sha1()
    s1.update(upwd.encode("utf-8"))
    upwd2 = s1.hexdigest()

    #创建对象
    user = UserInfo()
    user.uname = uname
    user.upwd = upwd2
    user.uemail = email
    user.save()

    #注册成功，转到登录界面
    return redirect('/user/login')

#判断账号是否已经存在(用ajax)
def register_exist(request):
    uname = request.GET.get('uname')
    #求出用户名的个数（不在乎具体内容）
    count = UserInfo.objects.filter(uname=uname).count()
    print(count)
    return JsonResponse({'count':count})



def login(request):
    uname=request.COOKIES.get('uname','')
    context={'title':'用户登录', 'error_name':0, 'error_pwd':0, 'uname':uname}
    return render(request, 'df_user/login.html', context)


def login_handle(request):
    #接收请求信息
    post = request.POST
    uname = post.get('username')
    upwd = post.get('pwd')
    #记住默认是选中的，如果不取消其值为1，就会把下面的默认0取代，如果取消，就为0
    jizhu = post.get('jizhu',1)
    #print(uname +" " +upwd)
    #根据用户名查询对象
    users = UserInfo.objects.filter(uname=uname) #返回的是列表[]

    #判断：如果未查到则用户名错，如果查到则判断是否正确
    if len(users)==1: #查到了，有且仅有一个
        #只有加密了才能和数据库中的对应
        s1=sha1()
        s1.update(upwd.encode('utf8'))
        if s1.hexdigest()==users[0].upwd:
            #如果url里面没有路径，就去/index
            url=request.COOKIES.get('url','/goods/index')
            ret = HttpResponseRedirect(url)
            #记住用户名
            if jizhu!=0:
                ret.set_cookie('uname', uname)
            else:
                ret.set_cookie('uname', '', max_age=-1)
            request.session['user_id']=users[0].id
            request.session['user_name'] = uname
            #设置session过期时间，0表示关闭浏览器就过期
            request.session.set_expiry(0)
            return ret
        else:                               #0表示用户名没错，1表示密码错误   uname和upwd是为了返回的时候输入框还有值
            context = {'title': '用户登录', 'error_name': 0, 'error_pwd':1 ,'uname':uname, 'upwd':upwd}
            return render(request, 'df_user/login.html', context)
    else:                                   #1表示用户名没错，0表示密码错误
        context = {'title': '用户登录', 'error_name': 1, 'error_pwd': 0, 'uname': uname, 'upwd': upwd}
        return render(request, 'df_user/login.html', context)

#退出
def logout(request):
    request.session.flush()
    return redirect('/goods/index')
    # try:
    #     # del request.session['user_id']
    #     # del request.session['user_name']
    # except KeyError:
    #     pass
    # return redirect('/user/login')

@user_decorator.login
def info(request):
    #获取用户邮箱信息
    user_email = UserInfo.objects.get(id=request.session['user_id']).uemail
    #最近浏览
    goods_ids = request.COOKIES.get('goods_ids', '')
    goods_list = []
    #先判断最近浏览是否为空,否则为空会报错
    if goods_ids !='' :
        goods_ids1 = goods_ids.split(',')
        for goods_id in goods_ids1:
            goods_list.append(GoodsInfo.objects.get(id=int(goods_id)))
    context={
        'title': '用户中心',
        'user_name':request.session['user_name'],
        'user_email':user_email,
        'page_name': 1,
        'info':True,
        'goods_list':goods_list,

    }
    return render(request, 'df_user/user_center_info.html', context)

@user_decorator.login
def site(request):
    user = UserInfo.objects.get(id=request.session['user_id'])

    #如果是get请求表示是直接通过链接来的
    if request.method=='POST':
        post = request.POST
        user.ushou = post.get('ushou')
        user.uaddress = post.get('uaddress')
        user.uyoubian = post.get('uyoubian')
        user.uphone = post.get('uphone')
        user.save()
    context = {
        'title' : '用户中心',
        'user':user,
        'page_name':1, #用来标识首页头部的不同（继承同一个base.html）
        'site':True,
    }
    return render(request, 'df_user/user_center_site.html', context)

@user_decorator.login
def order(request):
    #获取当前用户id
    uid = request.session.get('user_id')
    #查询当前用户的所有订单
    orderlist = OrderInfo.objects.filter(user_id=uid)

    context={
        'title':'用户中心',
        'page_name': 1,
        'order':True,
        'orderlist':orderlist,
    }
    return render(request, 'df_user/user_center_order.html', context)


#删除用户收货地址
def delete(request):
    uid = request.session.get('user_id')
    user = UserInfo.objects.get(id=uid)
    user.ushou = ''
    user.uaddress = ''
    user.uyoubian = ''
    user.uphone = ''
    user.save()
    return redirect('/user/site')
